package com.lagou.provider;

import com.lagou.provider.server.RpcServer;
import com.lagou.rpc.core.RpcZookeeperClient;
import com.lagou.rpc.core.config.RpcConfig;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

import javax.annotation.PreDestroy;
import java.net.InetAddress;

@ComponentScan(basePackages={"com.lagou"})
@SpringBootApplication
public class ServerBootstrapApplication implements CommandLineRunner {


    @Autowired
    private RpcServer rpcServer;

    @Autowired
    private RpcZookeeperClient zookeeperClient;

    @Autowired
    private RpcConfig rpcConfig;

    public static void main(String[] args) {
        SpringApplication.run(ServerBootstrapApplication.class, args);
    }


    @Override
    public void run(String... args) throws Exception {
        new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                InetAddress address = InetAddress.getLocalHost();
                rpcServer.startServer(address.getCanonicalHostName(), rpcConfig.getNettyPort());
            }
        }).start();
    }


    /**
     * springBoot关闭时，关闭zookeeper链接
     */
    @PreDestroy
    public void close(){
        zookeeperClient.close();
    }

}
